package com.jfinal.bbsapp.common.kit;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Calendar;
import java.util.Map;
import java.util.UUID;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import com.google.common.collect.Maps;
import com.jfinal.bbsapp.common.kit.FileUtils;
import com.jfinal.kit.PropKit;
import com.jfinal.upload.UploadFile;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FetchRet;
import com.qiniu.util.Auth;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;

public class FileUtils {
	private static final Logger logger = Logger.getLogger(FileUtils.class);
	private static final String ACCESS_KEY = PropKit.get("ACCESS_KEY");
	private static final String SECRET_KEY = PropKit.get("SECRET_KEY");
	private static final String BUCKET_NAME = PropKit.get("BUCKET_NAME"); // 默认上传空间
	private static final String Projectfolder = PropKit.get("Projectfolder"); // 默认上传项目文件夹
	private static final String BUCKET_HOST_NAME = PropKit.get("BUCKET_HOST_NAME"); // 空间默认域名
	
	//步步升用的七牛1区
	private static UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone1()));
	//private static UploadManager uploadManager = new UploadManager(new Configuration(Zone.zone2()));
	
	@SuppressWarnings("unused")
	private static int LIMIT_SIZE = 1000;


	public static String getBucketToken() {
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		String token = auth.uploadToken(BUCKET_NAME);
		return token;
	}
	
    public static String uploadFile(String filePath, String fileName) throws IOException {
		// 按照如下方式进行密钥配置
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		// 生成上传token
		String token = auth.uploadToken(BUCKET_NAME);
		File file = new File(filePath + fileName);
		InputStream is = new FileInputStream(file);
		byte[] byteData = IOUtils.toByteArray(is);
		
		Calendar calendar = Calendar.getInstance();
		// 获取当前年
		int year = calendar.get(Calendar.YEAR);  
		// 获取当前月
		int month = calendar.get(Calendar.MONTH) + 1;  
		// 获取当前日
		int day = calendar.get(Calendar.DATE);  
		//在空间中不能创建文件夹，但是为了区分不同的文件，可以这么做:
		//文件名以 2017/1/12/1.img , 即创建这样的虚拟目录 2017/1/12/ 做区分
		uploadManager.put(byteData,Projectfolder+"/"+ String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" + fileName, token);
		is.close();
		file.delete();
		file.deleteOnExit();
		return BUCKET_HOST_NAME + "/"+Projectfolder+ "/" + String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" + fileName;
	}

	public static String uploadContent(String fileName, String content) throws IOException {
		// 按照如下方式进行密钥配置
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		// 生成上传token
		String token = auth.uploadToken(BUCKET_NAME);
		byte[] byteData = content.getBytes("UTF-8");
		
		Calendar calendar = Calendar.getInstance();
		// 获取当前年
		int year = calendar.get(Calendar.YEAR);  
		// 获取当前月
		int month = calendar.get(Calendar.MONTH) + 1;  
		// 获取当前日
		int day = calendar.get(Calendar.DATE);  
		uploadManager.put(byteData, Projectfolder+"/"+ String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" +fileName, token);
		return BUCKET_HOST_NAME + "/"+Projectfolder+ "/" + String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" + fileName;
	}

	public static Map<String, Object> uploadQNFile(UploadFile _file) {
		Map<String, Object> map = Maps.newHashMap();
		String rs = "";
		String filePath = _file.getUploadPath() + File.separator;
		String fileName = _file.getFileName();
		File file = new File(filePath, fileName);
		String name = String.valueOf(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf('.'));
		File dest = new File(filePath, name);
		boolean b = file.renameTo(dest);
		try {
			if (b) {
				rs = uploadFile(filePath, name);
			}
		} catch (IOException e) {
			logger.error("------Exception------", e);
		}
		map.put("filename", name);
		map.put("filepath", rs);
		return map;
	}
	
	public static String getAQNFileName(UploadFile _file) {
		String rs = "";
		String filePath = _file.getUploadPath() + File.separator;
		String fileName = _file.getFileName();
		File file = new File(filePath, fileName);
		String name = String.valueOf(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf('.'));
		File dest = new File(filePath, name);
		boolean b = file.renameTo(dest);
		try {
			if (b) {
				rs = uploadFile(filePath, name);
			}
		} catch (IOException e) {
			logger.error("------Exception------", e);
		}
		return rs;
	}
	
	public static String upload(byte[] imageData, String fileName) {
		// 按照如下方式进行密钥配置
		Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
		// 生成上传token
		String token = auth.uploadToken(BUCKET_NAME);
		Calendar calendar = Calendar.getInstance();
		// 获取当前年
		int year = calendar.get(Calendar.YEAR);  
		// 获取当前月
		int month = calendar.get(Calendar.MONTH) + 1;  
		// 获取当前日
		int day = calendar.get(Calendar.DATE);  
		//在空间中不能创建文件夹，但是为了区分不同的文件，可以这么做:
		//文件名以 2017/1/12/1.img , 即创建这样的虚拟目录 2017/1/12/ 做区分
		try {
			com.qiniu.http.Response res = uploadManager.put(imageData,Projectfolder+"/"+ String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" + fileName, token);
			if (res.isOK() && res.isJson()) {// 返回这张存储照片的地址
				return BUCKET_HOST_NAME + "/"+Projectfolder+ "/" + String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" + fileName;
	        } else {
	            logger.error("七牛异常:" + res.bodyString());
	            return "";
	        }
		} catch (IOException e) {
			logger.error("------Exception------", e);
			 return "";
		}
	}
	
	public static String upload(String filePath, String fileName) {
		String rs = "";
		File file = new File(filePath + fileName);
		String name = String.valueOf(System.currentTimeMillis()) + fileName.substring(fileName.lastIndexOf('.'));
		File dest = new File(filePath, name);
		boolean b = file.renameTo(dest);
		try {
			if (b) {
				rs = uploadFile(filePath, name);
			}
		} catch (IOException e) {
			logger.error("------Exception------", e);
		}
		return rs;
	}
	
	public static String getAQNFileNameLocal(String filePath, String fileName) {
		String rs = "";
		File file = new File(filePath, fileName);
		String name = UUID.randomUUID().toString().replace("-", "") + fileName.substring(fileName.lastIndexOf('.'));
		File dest = new File(filePath, name);
		boolean b = file.renameTo(dest);
		try {
			if (b) {
				rs = uploadFile(filePath, name);
			}
		} catch (IOException e) {
			logger.error("------Exception------", e);
		}
		return rs;
	}

    public String getDownloadUrl(String targetUrl) {
    	Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        String downloadUrl = auth.privateDownloadUrl(targetUrl);
        return downloadUrl;
    }
    
    public static String download(String partid, String filepath, String url, String Filename) {
        String filepathname="";
    	OkHttpClient client = new OkHttpClient();
        //System.out.println(url);
        Request req = new Request.Builder().url(url).build();
        Response resp = null;
        try {
            resp = client.newCall(req).execute();
            //System.out.println(resp.isSuccessful());
            if(resp.isSuccessful()) {
                ResponseBody body = resp.body();
                InputStream is = body.byteStream();
                byte[] data = readInputStream(is);
                File filedate = new File(filepath);
                if (!filedate.exists() && !filedate.isDirectory()) {
                	filedate.mkdir();
                }
                
                File file = new File(filepath+"/"+partid);//创建视频片段文件夹
                if (!file.exists() && !file.isDirectory()) {
                	file.mkdir();
                }
                
                File imgFile = new File(file +"/"+ Filename);
                FileOutputStream fops = new FileOutputStream(imgFile);
                fops.write(data);
                fops.close();
                filepathname=filepath+"/"+partid+"/"+ Filename;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return filepathname;
            //System.out.println("Unexpected code " + resp);
        }
		return filepathname;
    }
   
    private static byte[] readInputStream(InputStream is) {
        ByteArrayOutputStream writer = new ByteArrayOutputStream();
        byte[] buff = new byte[1024 * 2];
        int len = 0;
        try {
            while((len = is.read(buff)) != -1) {
                writer.write(buff, 0, len);
            }
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return writer.toByteArray();
    }
    
    //抓取网络资源到空间
    public static String fetchret(String url) {
    	String refilename = "";
        Auth auth = Auth.create(ACCESS_KEY, SECRET_KEY);
        Zone z = Zone.zone2();
        Configuration c = new Configuration(z);
        BucketManager bucketManager = new BucketManager(auth, c);
        Calendar calendar = Calendar.getInstance();
		int year = calendar.get(Calendar.YEAR);  
		int month = calendar.get(Calendar.MONTH) + 1;
		int day = calendar.get(Calendar.DATE);
		String fileName = String.valueOf(System.currentTimeMillis())+".wav";
		String key = Projectfolder+"/"+ String.valueOf(year) + "/" + String.valueOf(month) + "/" + String.valueOf(day) + "/" +fileName;
        try {
            //调用fetch方法抓取文件
        	FetchRet fetchRet = bucketManager.fetch(url, BUCKET_NAME, key);
        	refilename = BUCKET_HOST_NAME + "/" + fetchRet.key;
        	//System.out.println(fetchRet.hash);
            //System.out.println(fetchRet.key);
            //System.out.println(fetchRet.mimeType);
            //System.out.println(fetchRet.fsize);
        } catch (QiniuException e) {
        	logger.error("------Exception------", e);
        }
        return refilename;
    }
}
